//
//  HomeViewController.m
//  HNAPayMobileSDK
//
//  Created by Ly_work on 15/11/25.
//  Copyright © 2015年 usolv. All rights reserved.
//

#import "HomeViewController.h"
#import <CommonCrypto/CommonDigest.h>

#import "HNAPayMobileSDKManager.h"

#import "HNAHudManager.h"

#import "HNARSAManager.h"


#define PLISTPATHSTRING [[NSBundle mainBundle] pathForResource:@"ParameterList" ofType:@"plist"]
#define PLISTPARAMETERSPLACEHOLDER @"parametersPlaceholder"
#define PLISTPARAMETERSTITLE @"parametersTitle"
#define PLISTKEYSARRAY @"parameterKey"
#define CELLTEXTFIELDTAG 998
#define CELLLABELTAG 999

@interface HomeViewController ()<UITextFieldDelegate>
@property (strong, nonatomic) IBOutlet UITableView *tableView;
@property (strong, nonatomic) NSMutableDictionary *dicParametersTitle;
@property (strong, nonatomic) NSMutableDictionary *dicParametersPlaceholder;
@property (strong, nonatomic) NSMutableArray *keysArray;
@property (strong, nonatomic) UITextField *activeTextfield;
@property (assign, nonatomic) CGRect oldR;

@property (strong, nonatomic) NSMutableDictionary *dicParameters;

@property (strong, nonatomic) HNAPayMobileSDKManager *hnaPayMobileSDKManager;
@property (strong, nonatomic) IBOutlet NSLayoutConstraint *topLayoutC;
@property (strong, nonatomic) IBOutlet NSLayoutConstraint *bottomLayoutC;

@end

static NSString *cellIndentifier = @"tbvIdentifier";

@implementation HomeViewController
#pragma mark ---iOS7以后方法，动态设置状态栏
- (UIStatusBarStyle)preferredStatusBarStyle
{
    return UIStatusBarStyleLightContent;
}
- (BOOL)prefersStatusBarHidden
{
    return NO;
}

#pragma mark ------viewController life cycle

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
    
}
- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    [self.tableView flashScrollIndicators];
}
- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    NSHTTPCookie *cookie;
    NSHTTPCookieStorage *storage = [NSHTTPCookieStorage sharedHTTPCookieStorage];
    NSLog(@"!!!!!!!!!!!!!!!!cookies===%@",[storage cookies]);
    
    NSDictionary *rootDic = [NSDictionary dictionaryWithContentsOfFile:PLISTPATHSTRING];
    NSDictionary *parametersTitle = [rootDic valueForKey:PLISTPARAMETERSTITLE];
    NSDictionary *parametersPlaceholder = [rootDic valueForKey:PLISTPARAMETERSPLACEHOLDER];
    NSArray *keys = [rootDic valueForKey:PLISTKEYSARRAY];
    self.dicParametersTitle = [NSMutableDictionary dictionaryWithDictionary:parametersTitle];
    self.dicParametersPlaceholder = [NSMutableDictionary dictionaryWithDictionary:parametersPlaceholder];
    self.keysArray = [NSMutableArray arrayWithArray:keys];
    
    self.dicParameters = [NSMutableDictionary dictionary];
    [self clearValueParamters];
}

#pragma mark ------keyboard will show or hide

- (void)keyboardWillShow:(NSNotification *)notification{
    NSDictionary *userInfo = [notification userInfo];
    NSValue* aValue = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
    CGRect keyboardRect = [aValue CGRectValue];
    keyboardRect = [self.view convertRect:keyboardRect fromView:nil];
    CGRect textfieldOnViewRect = [self.view convertRect:self.activeTextfield.frame fromView:self.activeTextfield.superview];
    CGFloat keyboardTop = keyboardRect.origin.y;
    CGFloat textfieldBottom = CGRectGetMaxY(textfieldOnViewRect);
    CGFloat moveH = 0;
    if (keyboardTop < textfieldBottom) {
        moveH = textfieldBottom - keyboardTop;
    }
    CGRect tbvR = self.tableView.frame;
    //    self.oldR = tbvR;
    tbvR.origin.y -= moveH;
    NSValue *animationDurationValue = [userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey];
    NSTimeInterval animationDuration;
    [animationDurationValue getValue:&animationDuration];
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationDuration:animationDuration];
    self.tableView.frame = tbvR;
    //    self.topLayoutC.constant -= moveH;
    //    self.topLayoutC.constant -= moveH;
    [UIView commitAnimations];
}
- (void)keyboardWillHide:(NSNotification *)notification{
    NSDictionary* userInfo = [notification userInfo];
    NSValue *animationDurationValue = [userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey];
    NSTimeInterval animationDuration;
    [animationDurationValue getValue:&animationDuration];
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationDuration:animationDuration];
    self.tableView.frame = (CGRect){0,60,[[UIScreen mainScreen] bounds].size.width,[[UIScreen mainScreen] bounds].size.height-60};
//    self.tableView.frame = self.oldR;
//    self.topLayoutC.constant = 0;
//    self.topLayoutC.constant = 0;
    [UIView commitAnimations];
}

#pragma mark ------Button Action

- (IBAction)resetAll:(id)sender {
    [self makeParamtersDefaultValues];
    /*
    0345597bcd25b43cd0008f92179a960e96930251a81a2cd84d36dba163e0aa3b43648e0fe3d493e3fb8b96e2446e2478630fc09b359cb57187f555bf22681ce07c341280376feec013e43a1d43d8e5acec625970a326033e1f2d390e98719ea0d5c0198ebcf45cb28541ad93270d535b9d370c91e30f094acc2bce64aac8c1ac
     */
//    HNARSAManager *rsa = [[HNARSAManager alloc] init];
//    NSString *rsaString = [rsa signTheDataSHA1WithRSA:@"tranCode=[MP01]version=[2.0]charset=[1]merId=[11000000000]virCardNoIn=[]merOrderNum=[52765893-92613]tranAmt=[10.00]merFeeAmt=[1.00]tranDateTime=[20151201095419]merUserId=[0000001]phone=[13699998888]idNumber=[430901123456789211]signType=[1]"];
//    NSLog(@"%@",rsaString);
    
//    NSString *s = [self getSignValueFromServer:@"tranCode=[MP01]version=[2.0]charset=[1]merId=[11000000050]virCardNoIn=[]merOrderNum=[52765893-92613]tranAmt=[10]merFeeAmt=[1]tranDateTime=[20151201095419]merUserId=[0000001]phone=[13699998888]idNumber=[430901123456789211]signType=[1]" custID:@"11000000050" signType:@"1"];
//    NSLog(@"sss==%@",s);
}

- (IBAction)saveAll:(id)sender {
    
}
- (IBAction)clearAll:(id)sender {
    [self clearValueParamters];
    [self.tableView reloadData];
}
- (IBAction)startPay:(id)sender {
    
    if (self.activeTextfield) {
        UITableViewCell *cell = [self getCellWithView:self.activeTextfield];
        NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
        [self updateParamtersWithIndexPath:indexPath textField:self.activeTextfield];
    }
    
    [self fillSignValue];
    
    NSLog(@"--------%@",self.dicParameters);
    
//    HNAPayMobileSDKManager *hnaPayMobileSDKManager1 = [[HNAPayMobileSDKManager alloc] init];
//    [hnaPayMobileSDKManager1 startHNAPayWithParameters:self.dicParameters finish:^(BOOL success) {
//        NSLog(@"HNAPayFinish:%d",success);
//        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"支付完成" message:nil delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
//        [alert show];
//    }];
    self.hnaPayMobileSDKManager = [[HNAPayMobileSDKManager alloc] init];
    [self.hnaPayMobileSDKManager startHNAPayWithParameters:self.dicParameters finish:^(void) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"支付流程关闭" message:nil delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
            [alert show];
    }];
}

- (NSString *)readPKeyFromePlist{
    NSArray *home = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [home objectAtIndex:0];
    NSString *plistPath = [documentsDirectory stringByAppendingPathComponent:@"pkey.plist"];
    NSLog(@"plistPath===%@",plistPath);
    NSFileManager *file = [NSFileManager defaultManager];
    if ([file fileExistsAtPath:plistPath])
    {
        NSLog(@"READ!!!!!");
        NSDictionary *plistD = [NSDictionary dictionaryWithContentsOfFile:plistPath];
        NSString *pkey = [plistD valueForKey:@"pkey"];
        return pkey;
    }
    else //若沙盒中没有
    {
        NSError *error;
        NSFileManager *fileManager = [NSFileManager defaultManager];
        NSString *bundle = [[NSBundle mainBundle] pathForResource:@"pkey" ofType:@"plist"];
        BOOL isOK = [fileManager copyItemAtPath:bundle toPath:plistPath error:&error];

        NSLog(@"是否写入成功：%d",isOK);
        return nil;
    }
}

#pragma mark ------UITextFieldDelegate

- (BOOL)textFieldShouldEndEditing:(UITextField *)textField{
    self.activeTextfield = nil;
    UITableViewCell *cell = [self getCellWithView:textField];
    NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
    [self updateParamtersWithIndexPath:indexPath textField:textField];
    return YES;
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    [textField resignFirstResponder];
    UITableViewCell *cell = [self getCellWithView:textField];
    NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
    [self updateParamtersWithIndexPath:indexPath textField:textField];
    return YES;
}
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField{
    self.activeTextfield = textField;
    return  YES;
}

#pragma mark ------signvalue MD5
-(NSString *)createSignValueString
{
    /*
     tranCode=[]version=[]charset=[]merId=[]virCardNoIn=[]merOrderNum=[]tranAmt=[]merFeeAmt=[]tranDateTime=[]merUserId=[]phone=[]idNumber=[]signType=[]
        &pkey=
     */
    NSArray *signKeysArray = @[@"tranCode",@"version",@"charset",@"merId",@"virCardNoIn",@"merOrderNum",@"tranAmt",@"merFeeAmt",@"tranDateTime",@"merUserId",@"buyerName",@"phone",@"idNumber",@"cardNo",@"signType",];
    NSString *signValueString = nil;
    __block  NSString *tempString = @"";
    [signKeysArray enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        NSString *value = [self.dicParameters valueForKey:obj];
        NSString *str = [NSString stringWithFormat:@"%@=[%@]",obj,value];
        tempString = [tempString stringByAppendingString:str];
    }];
    NSString *signType = [self.dicParameters valueForKey:@"signType"];
    NSString *merID = [self.dicParameters valueForKey:@"merId"];
//    signValueString = [self getSignValueFromServer:tempString custID:merID signType:signType];
    
    if ([signType isEqualToString:@"1"]) {
        signValueString = [self getSignValueFromServer:tempString custID:merID signType:signType];
//        signValueString = [self RSA:tempString];
    }else if ([signType isEqualToString:@"2"]){
        NSString *readPkey = [self readPKeyFromePlist];
        NSString *pkey = nil;
        if (readPkey) {
             pkey = [NSString stringWithFormat:@"&pkey=%@",readPkey];
        }else{
            NSString *tempPkey = [[NSDictionary dictionaryWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"pkey" ofType:@"plist"]] valueForKey:@"pkey"];
            pkey = [NSString stringWithFormat:@"&pkey=%@",tempPkey];
        }
        
        tempString = [tempString stringByAppendingString:pkey];
        signValueString = [self MD5:tempString];
    }
    NSLog(@"createSignValueString:%@",tempString);
    NSLog(@"MD5SignValueString:%@",signValueString);
    return signValueString;
}
- (NSString *)getSignValueFromServer:(NSString *)plainText custID:(NSString *)custID signType:(NSString *)signType{
    [[HNAHudManager sharedManager] showWithLabel:@"正在加密..."];
    NSString *dateString = nil;
    NSString *urlString = [NSString stringWithFormat:@"https://webtestdev3.hnapay.com/webtest/hnaMobilePaySign.do?custId=%@&str=%@&signType=%@",custID,plainText,signType];
    NSLog(@"++++++%@",urlString);
    NSURL *serverUrl = [NSURL URLWithString:urlString];
    NSURLRequest *request = [NSURLRequest requestWithURL:serverUrl];
    NSURLResponse *respone = nil;
    NSError *error = nil;
    //    NSURLConnection *connection = [NSURLConnection connectionWithRequest:request delegate:self];
    NSData *receiveData = [NSURLConnection sendSynchronousRequest:request returningResponse:&respone error:&error];
    [[HNAHudManager sharedManager] hideHUD];
    if ([receiveData length] > 0 && error == nil) {
        NSLog(@"数据长度：%lu",(unsigned long)[receiveData length]);
        dateString = [[NSString alloc] initWithData:receiveData encoding:NSUTF8StringEncoding];
        return dateString;
    }else if([receiveData length] == 0 && error == nil){
        NSLog(@"返回数据为空！");
    }else if (error != nil){
        NSLog(@"加密出错 = %@",error);
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:@"数据加密出错" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
        [alert show];
    }
    return nil;
}
- (NSString *)MD5:(NSString *)str
{
    const char *cStr = [str UTF8String];
    unsigned char result[CC_MD5_DIGEST_LENGTH];
    CC_MD5(cStr, (CC_LONG)strlen(cStr), result);
    
    NSMutableString *hashString = [NSMutableString string];
    for (int i = 0; i < CC_MD5_DIGEST_LENGTH; i++)
    {
        [hashString appendFormat:@"%02x", result[i]];
    }
    
    return [hashString lowercaseString];
}


#pragma mark ------获取订单时间和订单号
-(NSString *)getRandomNumber
{
    int n1 = [self getRandomNumber:10000000 to:99999999];
    int n2 = [self getRandomNumber:10000 to:99999];
    NSString *n = [NSString stringWithFormat:@"%d",n1];
    NSString *nn = [NSString stringWithFormat:@"%d",n2];
    
    n = [n stringByAppendingFormat:@"-%@",nn];
    return n;
}
-(int)getRandomNumber:(int)from to:(int)to
{
    return (int)(from + (arc4random() % (to - from + 1)));
}
-(NSString *)getCurrentDate
{
    NSDateFormatter *formatter =[[NSDateFormatter alloc] init];
    NSDate *date = [NSDate date];
    
    [formatter setDateFormat:@"yyyyMMddHHmmss"];
    NSString *str=[formatter stringFromDate:date];
    NSLog(@"str====%@",str);
    //20130716103344     33*60+44
    
    return str;
}

#pragma mark ------Get cell from view

- (UITableViewCell *)getCellWithView:(UIView *)childView{
    id tfSuper = childView;
    while (1) {
        tfSuper = [tfSuper superview];
        if ([tfSuper isKindOfClass:[UITableViewCell class]]) {
            break;
        }
    }
    UITableViewCell *cell = (UITableViewCell *)tfSuper;
    return cell;
}

#pragma mark ------update paramters

- (void)makeParamtersDefaultValues{
    
    [self.dicParameters setValue:@"MP01" forKey:@"tranCode"];
    [self.dicParameters setValue:@"2.0" forKey:@"version"];
    [self.dicParameters setValue:@"1" forKey:@"charset"];
    [self.dicParameters setValue:@"2" forKey:@"signType"];
    [self.dicParameters setValue:@"11000002989" forKey:@"merId"];
    [self.dicParameters setValue:@"" forKey:@"virCardNoIn"];
    
    [self.dicParameters setValue:@"10" forKey:@"tranAmt"];
    [self.dicParameters setValue:@"1" forKey:@"merFeeAmt"];
    [self.dicParameters setValue:@"1" forKey:@"currencyType"];
    [self.dicParameters setValue:@"http://www.xxx.com/response.do" forKey:@"returnUrl"];
    [self.dicParameters setValue:@"http://www.xxx.com/response.do" forKey:@"notifyUrl"];
    
    [self.dicParameters setValue:@"127.0.0.1" forKey:@"tranIP"];
    [self.dicParameters setValue:@"iPhone" forKey:@"goodsName"];
    [self.dicParameters setValue:@"iPhone100，只要998" forKey:@"goodsDetail"];
    [self.dicParameters setValue:@"0000001" forKey:@"merUserId"];
    [self.dicParameters setValue:@"13699998888" forKey:@"phone"];
    [self.dicParameters setValue:@"张三李四" forKey:@"buyerName"];
    [self.dicParameters setValue:@"430901123456789211" forKey:@"idNumber"];
    [self.dicParameters setValue:@"" forKey:@"merRemark"];
    
    [self.tableView reloadData];
}

//重置订单号
- (void)fillOrderNumber{
    NSString *merOrderNumber = [self getRandomNumber];
    [self.dicParameters setValue:merOrderNumber forKey:@"merOrderNum"];
}

//重置时间
- (void)fillTranDateTime{
    NSString *currentDateTime = [self getCurrentDate];
    [self.dicParameters setValue:currentDateTime forKey:@"tranDateTime"];
}
//重新生成加密域
- (void)fillSignValue{
    [self fillOrderNumber];
    [self fillTranDateTime];
    NSString *signValueString = [self createSignValueString];
    [self.dicParameters setValue:signValueString forKey:@"signValue"];
    [self.tableView reloadData];
}

- (void)clearValueParamters{
    [self.keysArray enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        [self.dicParameters setValue:@"" forKey:obj];
    }];
}

-(void)updateParamtersWithIndexPath:(NSIndexPath *)indexPath textField:(UITextField *)textField{
    NSString *key = [self.keysArray objectAtIndex:indexPath.row];
    //    NSString *value = [self.dicParameters valueForKey:key];
    [self.dicParameters setValue:textField.text forKey:key];
//    NSLog(@"%@",self.dicParameters);
}

#pragma mark ------Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return self.keysArray.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIndentifier forIndexPath:indexPath];
    UILabel *label = (UILabel *)[cell viewWithTag:CELLLABELTAG];
    UITextField *textfield = (UITextField *)[cell viewWithTag:CELLTEXTFIELDTAG];
    NSString *key = [self.keysArray objectAtIndex:indexPath.row];
    NSString *title = [self.dicParametersTitle valueForKey:key];
    NSString *placeholder = [self.dicParametersPlaceholder valueForKey:key];
    NSString *value = [self.dicParameters valueForKey:key];
    label.text = [NSString stringWithFormat:@"%@:",title];
    textfield.placeholder = placeholder;
    textfield.text = value;
    return cell;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
